﻿using System;

using Infrastructure.NetExtensions;

namespace TempEmployees.BLL.Validations
{
    public class IdentityNumber
    {
        private string m_id;

        public IdentityNumber(string id)
        {
            m_id = id;
            if (!IsValid(m_id)) throw new ValidationErrorException();
        }

        public override string ToString()
        {
            return m_id;
        }

        public static bool IsValid(string id)
        {
            string trimId = id.Trim();
            if (trimId.Length != 9) return false;
            short factor = 1;
            short idSum = 0;
            short tempShort;
            string tempStr;
            for (int i = 0; i < trimId.Length - 1; ++i)
            {
                if (!short.TryParse(trimId[i].ToString(), out tempShort))
                    return false;
                tempShort *= factor;
                if (factor == 1) factor = 2;
                else factor = 1;
                if (tempShort > 9)
                {
                    tempStr = tempShort.ToString();
                    idSum += short.Parse(tempStr[0].ToString());
                    idSum += short.Parse(tempStr[1].ToString());
                }
                else
                    idSum += tempShort;
            }
            if (!short.TryParse(trimId[trimId.Length - 1].ToString(), out tempShort))
                return false;
            if ((idSum.Cieling() - idSum) != tempShort)
                return false;
            return true;
        }

        public static bool IsValid(object data)
        {
            return IsValid(data as string);
        }
    }
}